<?php
namespace App\Admin\Controllers\Operation;

use App\Admin\Actions\Operation\ImportAdsSkuError;
use App\Admin\Actions\Operation\SyncAdsError;
use App\Admin\Extensions\Grid\Tool\Export;
use App\Models\AmazonAds\AdsError;
use App\Models\Basics\SysCountry;
use App\Util\RExcel;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Admin as SAdmin;
use Encore\Admin\Grid;
use Illuminate\Support\Facades\Request;

class AdsSyncErrorController extends AdminController{

    protected $title = '异常广告管理';

    protected function _style()
    {
        return <<<STYLE
.column-__actions__ {
    white-space: nowrap;
}
STYLE;
    }

    protected function grid()
    {
        SAdmin::style($this->_style());
        $grid = new Grid(new AdsError());
        $grid->model()->orderBy('id', 'DESC');
        $grid->column('id','ID')->sortable();
        $grid->column('report_date','日期');
        $grid->column('country.country','国家');
        $grid->column('sku_code','SKU');
        $grid->column('type','广告类型')->using(AdsError::$_type);
        $grid->column('error_field','异常字段');
        $grid->column('error_message','异常原因');
        $grid->column('status','广告状态')->using(AdsError::$_status);
        $grid->column('is_sync','是否同步')->using(AdsError::$_sync);

        $grid->fixHeader();
        $grid->fixColumns(0,-1);
        $grid->disableExport();
        $grid->disableCreateButton();
        $grid->disableActions();
        $grid->tools(function (Grid\Tools $tools){
            $tools->append(new ImportAdsSkuError()); //导入异常sku
            $tools->append(new Export('operation/ads-sync-error-download')); //导出
        });

        $grid->batchActions(function (Grid\Tools\BatchActions $batch) {
            $batch->disableDelete();
            $batch->add(new SyncAdsError());
        });


        $grid->filter(function($filter){
            $filter->column(1/2, function ($filter){
                $filter->where(function ($query) {
                    $query->where('error', 'like', "%{$this->input}%");
                }, '查询','sku8')->placeholder('模糊查询error.');
                $filter->equal('country_id', '国家')->select(SysCountry::options());
            });

            $filter->column(1/2, function ($filter){
                $filter->equal('type', '广告类型')->select(AdsError::$_type);
                $filter->equal('is_sync', '是否同步')->select(AdsError::$_sync);
                $filter->equal('status', '启用')->select(AdsError::$_status);
            });
        });

        return $grid;
    }

    public function download(){
        $request = Request::input();
        $query = $this->_initQuery($request);
        $this->_exeDownload($query);
    }

    private function _initQuery($filters){
        $query = AdsError::query()->orderBy('id', 'DESC');
        foreach ($filters as $key => $_filter){
            if($key == 'sku8'){
                $query->where(function ($query) use($_filter){
                    $query->where('error', 'like', "%{$_filter}%");
                });
            }

            if($key == 'status'){
                $query->where('status',$_filter);
            }

            if($key == 'country_id'){
                $query->where('country_id',$_filter);
            }
        }
        return $query;
    }

    private function _exeDownload($query){
        $head = ['日期','国家','广告类型','异常原因','广告状态','是否同步'];
        RExcel::exportCsv('广告异常数据',function () use ($head, $query) {
            $fp = fopen('php://output', 'w');
            fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));
            fputcsv($fp, $head);
            $query->chunk(1000, function ($re) use ($fp){
                $data = self::getDownloadData($re);
                foreach ($data as $item) {
                    fputcsv($fp, $item);
                }
            });
        });
    }

    public static function getDownloadData($res)
    {
        foreach ($res as $model){
            $temp = [
                $model->report_date,
                $model->country->country,
                AdsError::$_type[$model->type],
                $model->error,
                AdsError::$_status[$model->status],
                AdsError::$_sync[$model->is_sync],
            ];
            yield $temp;
        }
    }
}
